package pkg_member

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/pkg_member"
    pkg_memberReq "github.com/flipped-aurora/gin-vue-admin/server/model/pkg_member/request"
    "gorm.io/gorm"
)

type ActivateService struct {
}

// CreateActivate 创建活动管理/发布记录
// Author [piexlmax](https://github.com/piexlmax)
func (activateService *ActivateService) CreateActivate(activate *pkg_member.Activate) (err error) {
	err = global.GVA_DB.Create(activate).Error
	return err
}

// DeleteActivate 删除活动管理/发布记录
// Author [piexlmax](https://github.com/piexlmax)
func (activateService *ActivateService)DeleteActivate(ID string,userID uint) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
	    if err := tx.Model(&pkg_member.Activate{}).Where("id = ?", ID).Update("deleted_by", userID).Error; err != nil {
              return err
        }
        if err = tx.Delete(&pkg_member.Activate{},"id = ?",ID).Error; err != nil {
              return err
        }
        return nil
	})
	return err
}

// DeleteActivateByIds 批量删除活动管理/发布记录
// Author [piexlmax](https://github.com/piexlmax)
func (activateService *ActivateService)DeleteActivateByIds(IDs []string,deleted_by uint) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
	    if err := tx.Model(&pkg_member.Activate{}).Where("id in ?", IDs).Update("deleted_by", deleted_by).Error; err != nil {
            return err
        }
        if err := tx.Where("id in ?", IDs).Delete(&pkg_member.Activate{}).Error; err != nil {
            return err
        }
        return nil
    })
	return err
}

// UpdateActivate 更新活动管理/发布记录
// Author [piexlmax](https://github.com/piexlmax)
func (activateService *ActivateService)UpdateActivate(activate pkg_member.Activate) (err error) {
	err = global.GVA_DB.Save(&activate).Error
	return err
}

// GetActivate 根据ID获取活动管理/发布记录
// Author [piexlmax](https://github.com/piexlmax)
func (activateService *ActivateService)GetActivate(ID string) (activate pkg_member.Activate, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&activate).Error
	return
}

// GetActivateInfoList 分页获取活动管理/发布记录
// Author [piexlmax](https://github.com/piexlmax)
func (activateService *ActivateService)GetActivateInfoList(info pkg_memberReq.ActivateSearch) (list []pkg_member.Activate, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&pkg_member.Activate{})
    var activates []pkg_member.Activate
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

	if limit != 0 {
       db = db.Limit(limit).Offset(offset)
    }
	
	err = db.Find(&activates).Error
	return  activates, total, err
}
